package com.geek.novel.activity

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.geek.novel.R
import com.geek.novel.activity.auth.LoginActivity
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.adapter.BookSearchListAdapter
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.dialog.ConfirmDialog
import com.geek.novel.entity.BookRead
import com.geek.novel.network.RslHandler
import com.geek.novel.services.NovelService
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.view.loading.LoadingDialogUtil
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.geek.novel.vo.BookUserCollectVo
import com.geek.novel.vo.Pager
import kotlinx.android.synthetic.main.activity_collect.*


class CollectActivity: TitleBarActivity() , RslHandler {

	/**书籍列表*/
	private var bookList: ArrayList<BookRead> = ArrayList()

	/**当前页码，下标从0开始*/
	private var pageNo: Int = 0
	/**每页显示条数*/
	private var pageSize: Int = 10

	/**书籍列表的适配器*/
	private lateinit var collectBookAdapter: BookSearchListAdapter

	/**小说服务*/
	private lateinit var novelService: NovelService

	/**确认框*/
	private lateinit var confirmDialog: ConfirmDialog

	override fun pageName(): String{
		return AppContext.getContext().getString(R.string.title_bar_page_collect)
	}

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_collect)

		//设置背景为白色
		super.setBackgroundColor(Color.WHITE)

		//初始化服务对象
		novelService = NovelService(this)

		//初始化确认弹框
		this.initConfirmDialog()

		//初始化下拉刷新功能
		this.initRefreshLayout()

		//初始化列表
		this.initListView()

		//获取分类书籍数据
		this.queryBookByCollect()
	}


	/**初始化确认弹框*/
	private fun initConfirmDialog(){
		confirmDialog = ConfirmDialog(this)
		confirmDialog.setOnConfirmListener("去登录") {
			this.startActivityForResultByAnim(this, LoginActivity::class.java, Constant.ACTIVITY_RESULT_USER_LOGIN)
			confirmDialog.dismiss()
		}
	}


	/**获取分类书籍数据*/
	private fun queryBookByCollect() {
		LoadingDialogUtil.getInstance().showLoading("数据加载中...")
		//发起请求
		this.resetSearchBook()
		this.searchBook()
	}

	/**附加控件*/
	override fun attachViewChild() {
	}

	/**绑定事件*/
	override fun bindEventChild() {
	}

	/**重置搜索下标*/
	private fun resetSearchBook(){
		book_collect_refresh_layout.resetNoMoreData()
		this.pageNo = 0
		this.bookList.clear()
	}

	/**搜索*/
	private fun searchBook(){
		novelService.queryUserCollected(Pager.of(pageNo, pageSize))
		pageNo++
	}

	/**处理搜索结果*/
	private fun handleQueryResult(vo: BookUserCollectVo, view: View){
		try {
			val pager = vo.result ?: throw Exception("获取查询结果异常！")
			val records = pager.records ?: throw Exception("获取查询结果异常！")
			bookList.addAll(records)
			collectBookAdapter.notifyDataSetChanged()

			this.checkBookEmpty(view)
		} catch (e: Exception) {
			LogCatUtil.e("???", e.message, e)
			ToastUtils.toast(e.message)
		}
	}

	/**检查书籍列表是否为空*/
	private fun checkBookEmpty(view: View): Boolean{
		//书架列表为空的情况，添加书籍按钮
		if(bookList.isEmpty()){
			view.visibility = View.VISIBLE
		}else{
			view.visibility = View.GONE
		}
		return bookList.isEmpty()
	}

	/**
	 * 初始化下拉刷新功能
	 */
	private fun initRefreshLayout(){
		book_collect_refresh_layout.setRefreshHeader(book_collect_classics_header)
		book_collect_refresh_layout.setRefreshFooter(book_collect_classics_footer)
		//下拉刷新
		book_collect_refresh_layout.setOnRefreshListener {
			this.resetSearchBook()
			this.searchBook()
		}
		//滚动加载
		book_collect_refresh_layout.setOnLoadMoreListener{
			this.searchBook()
		}
	}


	/**初始化列表*/
	private fun initListView(){
		//添加适配器
		collectBookAdapter = BookSearchListAdapter(this, bookList)
		collectBookAdapter.initListView(rv_collect_books)
	}


	private fun showLoadingError(){
		LoadingDialogUtil.getInstance().dismiss()
		book_collect_refresh_layout.finishRefresh(false)
		book_collect_refresh_layout.finishLoadMore(false)
	}

	/**如果是从登录页面返回的，重新加载数据*/
	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)
		when(requestCode){
			//从登录页面返回的
			Constant.ACTIVITY_RESULT_USER_LOGIN->{
				this.searchBook()
			}
		}
	}

	override fun logout(key: Int) {
		when(key){
			//搜索结果
			Constant.HTTP_KEY_APP_USER_COLLECT_QUERY->{
				this.showLoadingError()
				confirmDialog.openDialog("授权失效，请重新登录后重试！")
			}
		}
	}

	override fun onError(code: Int, err: ApiErrorResult) {
		when(code){
			//搜索结果
			Constant.HTTP_KEY_APP_USER_COLLECT_QUERY->{
				this.showLoadingError()
			}
		}
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//搜索结果
			Constant.HTTP_KEY_APP_USER_COLLECT_QUERY->{
				LoadingDialogUtil.getInstance().dismiss()

				val bookUserCollectVo = result.getData() as BookUserCollectVo
				this.handleQueryResult(bookUserCollectVo, ly_book_collect_no_result)
				//处理下拉刷新
				book_collect_refresh_layout.finishRefresh(true)
				//处理滚动加载
				val noMoreData = bookUserCollectVo.result!!.totalPages-1 < pageNo
				book_collect_refresh_layout.finishLoadMore(0, true, noMoreData)
			}
		}
	}
	
}